<template>
  <div v-loading.fullscreen.lock="loading">
    <!--s 头部搜索栏 -->
    <div class="common-list-header__v2" ref="tableHeaderContainer">
      <div>
        <el-input class="search-input" :placeholder="$t('task.taskTypes.balance.searchTip')" v-model="searchModel.keyword">
          <el-button class="search-input__append" slot="append" @click="handleSearch">{{$t('common.base.search')}}</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams">{{$t('common.base.reset')}}</el-button>
      </div>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div class="common-list-view-header__v2" ref="tableDoContainer">
        <div class="common-list-view-header__v2-left">
          <el-radio-group v-model="balanceConfirm" @change="handleChangeBalance">
            <el-radio-button :label="2">{{$t('common.base.all')}}</el-radio-button>
            <el-radio-button :label="1">{{ $t('common.task.status.settled') }}</el-radio-button>
            <el-radio-button :label="0">{{ $t('common.task.status.unBalanced') }}</el-radio-button>
          </el-radio-group>
          <el-button type="primary" @click="batchBanlance" v-if="isNoBalance">
            {{ $t('task.taskTypes.balance.batchBalance') }}
          </el-button>
        </div>
        <div class="common-list-view-header__v2-right">
          <span class="el-dropdown-link cur-point mar-l-12" @click="showAdvancedSetting">
            {{$t('common.base.choiceCol')}}
            <i class="iconfont icon-fdn-select"></i>
          </span>
          <!-- start 更多操作按钮 -->
          <el-dropdown>
            <div class="task-ai task-flex task-font14 task-c6 task-pointer cur-point mar-l-16">
              <span class="task-mr4 task-ml4">{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="handleExport(false)">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="handleExport(true)">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- end 更多操作按钮 -->
        </div>
      </div>

      <!--s 表格 -->
      <el-table
        v-table-style
        ref="multipleTable"
        class="common-list-table__v2 mt_8"
        stripe
        :data="page.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.noData')"></BaseListForNoData>
        </template>
        <el-table-column type="selection" align="center"></el-table-column>
        <template v-for="(column, index) in columns">
          <el-table-column
            v-if="column.show"
            :key="`${column.field}_${index}`"
            :label="column.label"
            :prop="column.field"
            :width="column.width"
            :min-width="column.minWidth || '120px'"
            :sortable="column.sortable"
            :fixed="column.fixLeft || false"
            :align="column.align"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <template v-if="column.renderCell">
                <base-table-cell 
                  :render-cell="column.renderCell" 
                  :column="column" 
                  :row="scope.row">
                </base-table-cell>
              </template>
              <template v-else-if="column.field === 'orderNo'">
                <a
                  href=""
                  class="view-detail-btn"
                  v-if="scope.row.orderNo"
                  @click.stop.prevent="handleOpenTab(scope.row)">
                  {{ scope.row.orderNo }}
                </a>
              </template>
              <!-- 客户 -->
              <template v-else-if="column.field === 'customer'">
                {{ scope.row.customerName }}
              </template>
              <!-- 结算状态 -->
              <template v-else-if="column.field === 'balanceStatus'">
                <div class="view-status">
                  <span
                    v-if="scope.row.balanceStatus"
                    :class="{ 'unbalanced-status': scope.row.balanceStatus === '未结算' }"
                  >
                    {{ scope.row.balanceStatus }}
                  </span>
                </div>
              </template>
              <template v-else>
                {{ $formatFormField(column, scope.row) }}
              </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column fixed="right" :label="$t('common.base.operation')" width="120">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.balanceStatus === '未结算'" 
              @click.native.prevent="handleBalance(scope.row)" 
              type="text" 
              size="small"
            >
              {{ $t('common.base.settleAccounts') }}
            </el-button>
            <el-button 
              v-if="scope.row.balanceStatus === '已结算'" 
              @click.native.prevent="handleOpenTab(scope.row)" 
              type="text" 
              size="small"
            >
              {{ $t('common.base.view') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          {{ $t('goods.list.total') }}
          <span class="level-padding">{{ page.totalElements }}</span>
          {{ $t('common.base.piece') }}
        </div>
        <el-pagination
          class="product-table-pagination"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50]"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.totalElements"
        > </el-pagination>
      </div>
    </div>

    <!-- 选择列 -->
    <biz-select-column ref="advanced" @save="saveColumnStatus" />

    <!-- 导出弹窗 -->
    <base-export-group
      ref="exportPanelRef"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :needchoose-break="false"
      method="post"
      :action="orderSettleExport"
      :is-show-export-tip="isOpenData"
    />
    <biz-form-dialog
      ref="BizFormDiaLogComponent"
      :button-text="$t('task.taskTypes.balance.batchBalance')"
      :title="$t('task.auditSettle')"
      :footer-tip="$t('order.detailV2.balanceTip')"
      :fields="balanceFields"
      :submit-function="handleBatchBalanceSubmit"
    ></biz-form-dialog>
  </div>
</template>

<script>
import _ from 'lodash';
import i18n from '@src/locales';
import Page from '@model/Page';
import { orderSettleExport } from '@src/api/Export';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import { storageGet, storageSet } from '@src/util/storageV2';
import { getShopOrderDataList } from '@src/api/LinkcApi.js';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { getTaskBalanceFieldInfo } from '@src/api/TaskApi';
import { otherBalanceFields } from '@src/modules/task/taskTypes/balance/fields.js';
import BaseTableCell from 'packages/BaseTableCell';

export default {
  data() {
    return {
      loading: false,
      page: new Page(),
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
      },
      balanceFields: [],
      balanceConfirm: 0,
      columns: [],
      multipleSelection: [],
      orderSettleExport,
      isOpenData,
      selectedLimit: 500,
      tableContainerHeight: '460px',
    };
  },
  async mounted() {
    await this.buildColumns();
    this.handleSearch();

    // 获取结算自定义字段
    this.fetchBalanceFieldInfo();

    let that_ = this;
    this.$nextTick(() => {
      this.knowTableContainerHeight();
      window.onresize = _.debounce(() => {
        that_.knowTableContainerHeight();
      }, 500);
    });
  },
  computed: {
    exportColumns() {
      const exportColumns = this.otherBalanceFields.filter(v => v.export);
      exportColumns.forEach(v => {
        v.label = v.displayName;
        v.exportAlias = v.fieldName;
      });

      let arr = [
        {
          label: this.$t('event.detail.text3'),
          value: 'mallExport',
          columns: exportColumns,
        },
      ];
      return arr;
    },
    selectedIds() {
      return this.multipleSelection.map(v => v.id) || [];
    },
    otherBalanceFields() {
      return otherBalanceFields.filter(v => v.isMallShow) || [];
    },
    /** 
     * @description 是否为未结算
    */
    isNoBalance() {
      return this.balanceConfirm === 0
    },
  },
  methods: {
    async handleSearch() {
      try {
        this.loading = true;
        
        const balanceStatus = this.balanceConfirm === 2 ? '' : ~~this.balanceConfirm;
        const { code, result } = await getShopOrderDataList({
          ...this.searchModel,
          balanceStatus
        });

        if (code !== 0) {
          this.loading = false;
          this.page = this.$options.data.call(this).page;
          return this.$message.error(this.$t('goods.tips.queryListFailed'));
        }

        const { pageNum, list, total, pageSize } = result;
        [this.page['list'], this.page['totalElements'], this.page['pageNum'], this.page['pageSize']] = [list, total, pageNum, pageSize];

        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('fetch goods list error', error);
      }
    },
    resetParams() {
      const option = this.$options.data.call(this);
      this.searchModel = option.searchModel;
      this.balanceConfirm = option.balanceConfirm;
      this.page = option.page;

      this.handleSearch();
    },
    handleChangeBalance() {
      this.handleSearch();
    },
    batchBanlance() {
      if (!this.multipleSelection.length) {
        return this.$platform.alert(this.$t('task.taskTypes.balance.selectTip'));
      }

      if (this.balanceFields.length) {
        this.$refs.BizFormDiaLogComponent?.outsideShow();
      } else {
        this.$confirm(this.$t('task.tip.settlementTip10'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.makeSure'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning',
        })
          .then(() => {
            this.handleBatchBalanceSubmit({});
          })
          .catch(() => {});
      }
    },
    handleBatchBalanceSubmit(balanceFormData) {
      const packFormData = this.pack(balanceFormData);
      const params = {
        ...packFormData,
        ids: this.selectedIds.join(','),
      };

      console.log('params', params)
      // batchBalanceTask(params)
      //   .then((result) => {
      //     const isSuccess = result?.succ
      //     // 失败
      //     if (!isSuccess) {
      //       return Platform.alert(result.message)
      //     }

      //     // 成功提示
      //     Platform.alert(BATCH_BALANCE_SUCCESS_MESSAGE)
      //     // 关闭批量结算弹窗
      //     this.BizFormDiaLogComponent?.outsideClose()
      //     this.refresh()
      //   })
    },
    // 将数据打包成服务器可接收的数据
    pack(form) {
      let data = {};
      let attribute = {};
      let attachment = {};

      this.balanceFields.forEach(field => {
        if (field.formType == 'attachment') {
          attachment = form[field.fieldName];
        } else {
          attribute[field.fieldName] = form[field.fieldName];
        }
      });

      // 要对attachment校验一下 空对象foreach会报错
      Object.keys(attachment).length > 0
        && attachment.forEach((item, index) => {
          data[`balanceAttachments[${index}]`] = item;
        });

      data.balanceAttributes = attribute;
      return data;
    },
    /** 打开选择列 */
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    handleExport(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}商品数据.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length) return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanelRef.open(ids, fileName);
    },
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { mallExport } = checkedMap;
      const exportAll = !ids || !ids.length;

      const params = {
        checked: mallExport.join(','),
        ids: ids.join(','),
        exportSearchModel: JSON.stringify(this.searchModel),
        dataTotal: exportAll ? this.page.totalElements : this.selectedIds.length,
      };

      return params;
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max ? this.$t('common.base.exportModal.oversizeTips', { size: '5000' }) : null;
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    getLocalStorageData() {
      const dataStr = storageGet('mallBalance_list_localStorage') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('mallBalance_list_localStorage', JSON.stringify(data));
    },
    handleSelection(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter(ms => this.page.list.some(cs => cs.id === ms.id));

      let unSelected = this.page.list.filter(c => original.every(oc => oc.id !== c.id));

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.maxDataCanChooseTips', { data1: this.selectedLimit }));
      }

      this.multipleSelection = tv;

      this.$nextTick(() => {
        this.knowTableContainerHeight();
      });
    },
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter(ms => this.page.list.every(c => c.id !== ms.id));
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    sortChange(option) {
      try {
        const { prop, order } = option;
        if (!order) {
          this.searchModel.orderDetail = {};
          return this.handleSearch();
        }
        const sortedField = this.otherBalanceFields.filter(sf => sf.fieldName === prop)[0] || {};

        let isSystem = 0;

        if (prop === 'createTime' || prop === 'updateTime') {
          isSystem = 1;
        } else {
          isSystem = sortedField.isSystem;
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column: isSystem ? `${prop}` : prop,
        };

        if (prop === 'createTime' || prop === 'updateTime' || sortedField.formType === 'date' || sortedField.formType === 'datetime') {
          sortModel.type = 'date';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.searchModel.orderDetail = sortModel;

        this.handleSearch();
      } catch (e) {
        console.error('e', e);
      }
    },
    // 构建列表表头
    buildColumns() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];

      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      let fields = [...this.otherBalanceFields].sort((a, b) => a.orderId - b.orderId);
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }

      this.columns = fields
        .filter(v => v.fieldName !== 'hasInventory' && v.show)
        .map(field => {
          let sortable = false;
          let minWidth = null;

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (['consigneePhone'].includes(field.fieldName)) minWidth = 130;

          if (['orderNo', 'balanceTime', 'orderTime'].includes(field.fieldName)) {
            minWidth = 160;
          }

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map(col => {
          let show = col.show === true;
          let { width } = col;
          let localField = (localColumns[col.field] && localColumns[col.field].field) || null;

          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            width = typeof localField.width == 'number' ? `${localField.width}px` : `${localField.width}`.indexOf('px') ? localField.width : '';
            show = localField.show !== false;
          }

          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left';
          return col;
        });

      // return this.columns;
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      // 存储列数据之后，如果存在列被删除的情况，可能产生空值，需要过滤，否则其他地方没做判断会报错
      return fields.filter(v => v).concat(unsortedFields);
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.handleSearch();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.handleSearch();
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight() {
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`);
    },
    handleOpenTab(row, isOpen = false) {
      if (!row.orderId) return;

      let fromId = window.frameElement.getAttribute('id');

      const params = isOpen ? `id=${row.orderId}&isBalance=true` : `id=${row.orderId}`;
      openAccurateTab({
        type: PageRoutesTypeEnum.PageOrderDetailV2,
        key: row.orderId,
        // titleKey: row.orderNum,
        params,
        fromId,
      });
    },
    handleBalance(row) {
      this.handleOpenTab(row, true);
    },
    // 获取结算自定义字段数据
    fetchBalanceFieldInfo() {
      getTaskBalanceFieldInfo().then(result => {
        // TODO
        // 是否启用工单自定义结算字段
        const openUserDefinedBalance = true;
        const balanceFields = openUserDefinedBalance ? result || [] : [];
        // 给结算自定义字段一个标识符，用于高级搜索的时候判断是否是结算自定义字段
        balanceFields.forEach(item => {
          item.isBalanceField = true;
        });
        this.balanceFields = balanceFields.filter(field => field.setting.isOpen);
      });
    },
  },
  components: {
    [BaseTableCell.name]: BaseTableCell,
  },
};
</script>

<style lang="scss" scoped>
.view-status {
  span {
    display: block;
    min-width: 52px;
    height: 22px;
    line-height: 22px;
    text-align: center;
    background: #07C160;
    border-radius: 11px;
    font-size: 12px;
    color: #fff;
    padding:0 8px 0 8px;
  }

  .unbalanced-status {
    background: #FFAE00;
  }
}
</style>
